package com.anda.driver.locator.service;

import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager.WakeLock;
import android.util.Log;

import com.anda.driver.locator.receiver.AlarmReceiver;
import com.anda.driver.util.CommUtil;

public class AlarmManagerService extends Service {
	private static final String _TAG = AlarmManagerService.class.getName();
	private static WakeLock wakeLock = null;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		wakeLock= CommUtil.acquireWakeLock(this, wakeLock, _TAG);
		super.onCreate();
		Log.d(_TAG,"onCreate");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		CommUtil.releaseWakeLock(wakeLock, _TAG);
		Log.d(_TAG,"onDestroy");
	}

//	@Override
//	public void onStart(Intent intent, int startId) {
//		super.onStart(intent, startId);
//		long after = intent.getLongExtra("after", 5 * 1000L);
//		setAlarm(after);
//		Log.d(_TAG,"onStart");
//	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		long after = intent.getLongExtra("after", 5 * 1000L);
		setAlarm(after);
		Log.d(_TAG,"onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

	private void setAlarm(long after){
//		Intent intent = new Intent(this, DriverLocatorCellService.class);
//		PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
		Intent intent = new Intent(this, AlarmReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		long l = System.currentTimeMillis() + after;
		alarmManager.set(AlarmManager.RTC_WAKEUP, l , pi);
		Log.d(_TAG,"set Alarm on "+CommUtil.getDateStringFormat17(new Date(l)));
		stopSelf();
	}
	
}
